package com.dna.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dna.entity.DictEntity;
import com.dna.mapper.DictMapper;
import com.dna.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public List<DictEntity> queryAll() {
        List<DictEntity> dictList = buildDictTree(dictMapper.selectAll(), 0L);
        return dictList;
    }

    public List<DictEntity> buildDictTree(List<DictEntity> list, Long id) {
        List<DictEntity> subDictList = Lists.newArrayList();

        for (DictEntity dict : list) {
            if (id == dict.getParentId()) {
                dict.setChildren(buildDictTree(list, dict.getId()));
                subDictList.add(dict);
            }
        }
        return subDictList;
    }

    @Override
    public DictEntity queryOne(DictEntity dictEntity) {
        return dictMapper.selectOne(dictEntity);
    }

    @Override
    @Transactional
    public void save(DictEntity dictEntity) {
        dictMapper.insertSelective(dictEntity);
    }

    @Override
    @Transactional
    public void update(DictEntity dictEntity) {
        dictMapper.updateByPrimaryKeySelective(dictEntity);
    }

    @Override
    public void delete(Set<Long> ids) {
        List<DictEntity> dictList = dictMapper.selectAll();

        Set<Long> dictSet = Sets.newHashSet(ids);
        dictSet = getDictIds(dictList, ids, dictSet);

        Example example = new Example(DictEntity.class);
        Criteria criteria = example.createCriteria();
        criteria.andIn("id", dictSet);

        dictMapper.deleteByExample(example);
    }

    private Set<Long> getDictIds(List<DictEntity> dictList, Set<Long> ids, Set<Long> dictSet) {
        if (ids.isEmpty()) {
            return dictSet;
        }

        Set<Long> startIds = new HashSet<>(ids);

        for (Long id : ids) {
            for (DictEntity dict : dictList) {
                if (id.intValue() == dict.getParentId().intValue()) {
                    dictSet.add(dict.getId());
                    startIds.add(dict.getId());
                }
            }
            startIds.remove(id);
        }
        return getDictIds(dictList, startIds, dictSet);
    }

}
